package com.zy.fee.roadpark.activity.np;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.flyco.roundview.RoundLinearLayout;
import com.flyco.roundview.RoundTextView;
import com.zy.fee.roadpark.R;
import com.zy.fee.roadpark.config.Constants;
import com.zy.fee.roadpark.dao.NpNodeRecordLogic;
import com.zy.fee.roadpark.model.M_Node;
import com.zy.fee.roadpark.model.apimodel.APIM_NodeRecordInfo;
import com.zy.fee.roadpark.model.apimodel.APIM_NpNodeRecordList;
import com.zy.fee.roadpark.util.Printer;
import com.zy.fee.roadpark.view.CommonDialog;
import com.zygk.library.base.BaseActivity;
import com.zygk.library.util.ColorUtil;
import com.zygk.library.util.Convert;
import com.zygk.library.util.DateTimeUtil;
import com.zygk.library.util.HttpRequest;
import com.zygk.library.util.PreferencesHelper;
import com.zygk.library.util.StringUtils;
import com.zygk.library.util.ToastUtil;
import com.zygk.library.view.AutoResizeTextView;
import com.zygk.library.view.gridpasswordview.GridPasswordView;

/**
 * Created by Wikison on 2019/4/3.
 * 收款
 */
public class NpNodeReceivablesActivity extends BaseActivity {
  private static final int WAIT = 0x001;

  @BindView(R.id.tv_right) TextView tvRight;
  @BindView(R.id.lh_tv_title) TextView lhTvTitle;
  @BindView(R.id.rll_code) RoundLinearLayout rllCode;
  @BindView(R.id.et_code) EditText etCode;
  @BindView(R.id.gpvPlateNumber) GridPasswordView gpvPlateNumber;
  @BindView(R.id.tv_hint) TextView tvHint;
  @BindView(R.id.tv_park_time) AutoResizeTextView tvParkTime;
  @BindView(R.id.iv_photo) ImageView ivPhoto;
  @BindView(R.id.tv_money) TextView tvMoney;
  @BindView(R.id.tv_money_payed) TextView tvMoneyPayed;
  @BindView(R.id.tv_to_pay) TextView tvToPay;
  @BindView(R.id.rtv_left) RoundTextView rtvLeft;
  @BindView(R.id.tv_print) RoundTextView rtvPrint;
  @BindView(R.id.rtv_right) RoundTextView rtvRight;
  @BindView(R.id.ll_month_info) LinearLayout llMonthInfo;
  @BindView(R.id.tv_month_day) TextView tvMonthDay;
  @BindView(R.id.tv_month_left) TextView tvMonthLeft;

  private M_Node mNode;
  private APIM_NodeRecordInfo nodeRecord;
  private CountDownTimer timer;

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
  }

  @Override public void setContentView() {
    setContentView(R.layout.activity_np_node_receivables);
  }

  @Override public void init() {
    initData();
    initView();
    initListener();
  }

  private void initData() {
    registerReceiver(new String[] { Constants.BROADCAST_FORENSICS_SUCCESS });

    mNode = (M_Node) getIntent().getSerializableExtra(NpSpotListActivity.INTENT_NODE);
    nodeRecordInfo();
  }

  private void initView() {
    lhTvTitle.setText("收款");

    gpvPlateNumber.setPassword(mNode.getCarNumber());
    gpvPlateNumber.setEnabled(false);
    gpvPlateNumber.setClickable(false);
  }

  private void initListener() {
    gpvPlateNumber.togglePasswordVisibility();
  }

  private void printTicket() {
    if (nodeRecord == null) {
      return;
    }

    try {
      Printer.printT(nodeRecord.getCarNumber(), nodeRecord.getStartTime(), Constants.PAY_NP_URL + mNode.getNodeRecordID(), true, preferencesHelper.getSettingString(PreferencesHelper.User.Key.LOT_ID));
      ToastUtil.showMessage(mContext, "小票打印成功!");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  // 倒计时60s
  private void waitForRefresh() {
    timer = new CountDownTimer(61 * 1000, 1000) {
      @Override public void onTick(long millisUntilFinished) {

        tvRight.setText("" + millisUntilFinished / 1000 + "");
      }

      @Override public void onFinish() {
        nodeRecordInfo();
      }
    }.start();
  }

  private void nodeRecordInfo() {
    NpNodeRecordLogic.npnode_record_info(mContext, mNode.getNodeRecordID(),
        new HttpRequest.HttpCallback() {
          @Override public void onStart() {
            showNoCancelPd();
            if (timer != null) {
              timer.cancel();
            }
          }

          @Override public void onSucceed(Object obj) {
            APIM_NodeRecordInfo result = (APIM_NodeRecordInfo) obj;
            nodeRecord = result;
            waitForRefresh();
            setRecordInfo();
          }

          @Override public void onFailed() {

          }

          @Override public void onFinish() {
            dismissPd();
          }
        });
  }

  private void getNodeRecordState(int pay2escape) {
    NpNodeRecordLogic.npnode_record_info(mContext, mNode.getNodeRecordID(),
        new HttpRequest.HttpCallback() {
          @Override public void onStart() {
            showNoCancelPd();
          }

          @Override public void onSucceed(Object obj) {
            APIM_NodeRecordInfo result = (APIM_NodeRecordInfo) obj;
            if (result.getRecordStatus() == 1) {
              ToastUtil.showMessage(mContext, "该订单已支付完成，无法继续操作");
              sendBroadcast(new Intent(Constants.BROADCAST_REFRESH_NODE_LIST));
              rtvLeft.getDelegate()
                  .setBackgroundColor(ColorUtil.getColor(mContext, R.color.font_black_999));
              rtvRight.getDelegate()
                  .setBackgroundColor(ColorUtil.getColor(mContext, R.color.font_black_999));
              rtvLeft.setEnabled(false);
              rtvRight.setEnabled(false);
              return;
            } else if (result.getRecordStatus() == 0) {
              if (pay2escape == 0) {
                CommonDialog.showConfirmPayDialog(mContext, mNode.getCarNumber(),
                    nodeRecord.getMoney() - nodeRecord.getPayMoney(), "取消", "确定", () -> {
                      record_pay_admin();
                    }, () -> {
                    });
              } else if (pay2escape == 1) {
                npnode_record_apply_list(mNode.getCarNumber());
              } else if (pay2escape == 2) {
                if (null == nodeRecord) {
                  ToastUtil.showMessage(mContext, "订单不存在");
                  return;
                }
                if (nodeRecord.getMoney() - nodeRecord.getPayMoney() == 0) {
                  ToastUtil.showMessage(mContext, "当前未支付金额为0, 无需缴费");
                  return;
                }
                String qrUrl =
                    Constants.PAY_NP_URL + mNode.getNodeRecordID();
                CommonDialog.showQrCodeDialog(mContext, qrUrl, mNode.getCarNumber(),
                    nodeRecord.getMoney() - nodeRecord.getPayMoney());
                sendBroadcast(new Intent(Constants.BROADCAST_DIALOG_PAY));
              }
            }
          }

          @Override public void onFailed() {

          }

          @Override public void onFinish() {
            dismissPd();
          }
        });
  }

  /**
   * 获取申请驶离的停车单列表
   */
  private void npnode_record_apply_list(String carNumber) {
    String handleDate = null;
    NpNodeRecordLogic.npnode_record_apply_list(mContext, 0, carNumber, handleDate,
      1, Constants.ROWS, new HttpRequest.HttpCallback() {
        @Override public void onStart() {
          showNoCancelPd();
        }

        @Override public void onSucceed(Object obj) {
          APIM_NpNodeRecordList result = (APIM_NpNodeRecordList) obj;
          // 有未处理的申请驶离的停车单
          if(result.getAllNum() > 0) {
            CommonDialog.showYesOrNoDialog(mContext, "车辆" + mNode.getCarNumber() + "存在申请驶离未处理记录，前去处理？", "取消", "去处理",
              () -> {
                Intent intent = new Intent(mContext, LeaveApplyActivity.class);
                intent.putExtra("carNumber", mNode.getCarNumber());
                startActivity(intent);
              },
              null);
          } else {
            CommonDialog.showYesOrNoWithTitleDialog(mContext, "", "确定未付款(逃逸)?", "取消", "确定",
              () -> {
                set_escape();
              }, () -> {
              });
          }
        }

        @Override public void onFailed() {

        }

        @Override public void onFinish() {
          dismissPd();
        }
      });
  }

  private void setRecordInfo() {
    if(StringUtils.isBlank(nodeRecord.getCode())){
      rllCode.setVisibility(View.GONE);
    }else{
      rllCode.setVisibility(View.VISIBLE);
      etCode.setText(nodeRecord.getCode());
      etCode.setEnabled(false);
    }
    tvHint.setVisibility(nodeRecord.getEscape() == 1 ? View.VISIBLE : View.GONE);
    tvParkTime.setText(DateTimeUtil.getSecondsFormat(nodeRecord.getSeconds()));
    imageManager.loadUrlImage(nodeRecord.getPic(), ivPhoto);
    tvMoney.setText(Convert.getMoneyString(nodeRecord.getMoney()));
    tvMoneyPayed.setText(Convert.getMoneyString(nodeRecord.getPayMoney()));
    tvToPay.setText(Convert.getMoneyString(nodeRecord.getMoney() - nodeRecord.getPayMoney()));
    if (nodeRecord.getIsMonth() == 1) {
      llMonthInfo.setVisibility(View.VISIBLE);
      tvMonthDay.setText(
          "包月到期: " + DateTimeUtil.getDateByAddMinute(nodeRecord.getStartTime(),
              nodeRecord.getMonthMin())
              .substring(0, 10));
      tvMonthLeft.setText("包月剩余: " + nodeRecord.getMonthMin() / 1440 + "天");
    } else {
      llMonthInfo.setVisibility(View.GONE);
    }
  }

  private void record_pay_admin() {
    NpNodeRecordLogic.npnode_record_pay_admin(mContext, preferencesHelper.userManager().getUserID(),
        mNode.getNodeRecordID(), nodeRecord.getMoney() - nodeRecord.getPayMoney(),
        new HttpRequest.HttpCallback() {
          @Override public void onStart() {
            showNoCancelPd();
          }

          @Override public void onSucceed(Object obj) {
            ToastUtil.showMessage(mContext, "已完成线下收款");
            sendBroadcast(new Intent(Constants.BROADCAST_REFRESH_NODE_LIST));
            if (nodeRecord.getEscape() == 1) {
              //有逃逸单跳转到追缴列表
              Intent intent = new Intent(mContext, NpOverpayBillListActivity.class);
              intent.putExtra(NpOverpayBillListActivity.INTENT_PLATE_NUMBER, mNode.getCarNumber());
              startActivity(intent);
            }
            finish();
          }

          @Override public void onFailed() {
            ToastUtil.showNetErrorMessage(mContext);
          }

          @Override public void onFinish() {
            dismissPd();
          }
        });
  }

  private void set_escape() {
    NpNodeRecordLogic.npnode_set_escape(mContext, mNode.getNodeRecordID(),
        new HttpRequest.HttpCallback() {
          @Override public void onStart() {
            showNoCancelPd();
          }

          @Override public void onSucceed(Object obj) {
            ToastUtil.showMessage(mContext, "设置逃逸成功");
            sendBroadcast(new Intent(Constants.BROADCAST_REFRESH_NODE_LIST));
            Intent intent = new Intent(mContext, NpOverpayBillListActivity.class);
            intent.putExtra(NpOverpayBillListActivity.INTENT_PLATE_NUMBER, mNode.getCarNumber());
            startActivity(intent);

            finish();
          }

          @Override public void onFailed() {
            ToastUtil.showNetErrorMessage(mContext);
          }

          @Override public void onFinish() {
            dismissPd();
          }
        });
  }

  @Override protected void handleReceiver(Context context, Intent intent) {
    super.handleReceiver(context, intent);
    if (intent == null || TextUtils.isEmpty(intent.getAction())) {
      return;
    }
    if (Constants.BROADCAST_FORENSICS_SUCCESS.equals(intent.getAction())) {
      finish();
    }
  }

  @OnClick({ R.id.ll_back, R.id.rtv_left, R.id.rtv_right, R.id.iv_code, R.id.tv_print })
  public void onViewClicked(View view) {
    switch (view.getId()) {
      case R.id.ll_back:
        finish();
        break;
      case R.id.iv_code:
        getNodeRecordState(2);
        break;
      case R.id.rtv_left:
//        getNodeRecordState(0); // 线下收款去掉
        getNodeRecordState(2);
        break;
      case R.id.rtv_right:
        getNodeRecordState(1);
        break;
      case R.id.tv_print:
        CommonDialog.showYesOrNoWithTitleDialog(mContext, "", "是否补打小票", "是", "否", () -> {
        }, () -> {
          printTicket();
        });
        break;
    }
  }

  @Override protected void onDestroy() {
    super.onDestroy();
    if (timer != null) timer.cancel();
  }
}
